package com.destroyer.system.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.destroyer.core.config.oss.AlyOssConfig;
import com.destroyer.common.entity.system.Result;
import com.destroyer.system.entity.SignQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/destroyer/system/oss")
@Api(value = "OssController", tags = "阿里云配置")
public class OssController {
    @Autowired
    OSS client;
    @Autowired
    AlyOssConfig ossConfig;

    /**
     * 生成一个预签名的url，给前端js上传
     * 参考官网文档： https://help.aliyun.com/document_detail/32016.html
     *
     * @param fileName 上传到oss的文件相对路径
     * @param mime 签名里会加入contentType进行计算，因此此参数必须
     * @return 签名后的url
     */
    @GetMapping("/sign")
    @CrossOrigin
    @ApiOperation(value = "获取阿里云上传url", notes = "mime配置：https://help.aliyun.com/zh/oss/user-guide/configure-the-content-type-header")
    public Result<String> preUploadFile(@RequestParam @ApiParam(value = "相对路径", required = true) String fileName,
                                        @RequestParam @ApiParam(value = "文件类型", required = true) String mime) {
        // 设置请求头。
        Map<String, String> headers = new HashMap<>();
        // 指定ContentType，注意：必须指定，这个header加入签名了，不指定时前端带Content-Type上传，会导致签名验证不通过
        headers.put(OSSHeaders.CONTENT_TYPE, mime);
        // 生成签名URL。
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ossConfig.getBucket(), fileName, HttpMethod.PUT);
        // 设置过期时间1小时。
        request.setExpiration(DateUtil.offsetHour(new Date(), 1));
        // 将请求头加入到request中。
        request.setHeaders(headers);
        return Result.success(client.generatePresignedUrl(request).toString());
    }

    @PostMapping("/sign")
    @CrossOrigin
    @ApiOperation(value = "获取阿里云上传url", notes = "mime配置：https://help.aliyun.com/zh/oss/user-guide/configure-the-content-type-header")
    public Result<String> getUploadFile(@RequestBody SignQuery req) {
        return preUploadFile(req.getFileName(), req.getMime());
    }


}
